/*************************************************************************
 * File Name:    Convert_Sorted_Array_to_Binary_Search_Tree.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/4 14:20:57
 * 
 * Description:  
 |-----------------------------------------------------------------------
 | Problem: Convert Sorted Array to Binary Search Tree
 | Given an array where elements are sorted in ascending order,
 | convert it to a height balanced BST.
 |-----------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *sortedArrayToBST(vector<int> &num)
    {
        TreeNode *root;
        dfs(root, 0, num.size() - 1, num);
        return root;
    }
    
    void dfs(TreeNode* &root, int left, int right, const vector<int> &num)
    {
        if (left > right) {
            root = NULL;
            return;
        }
        int mid = (left + right) / 2;
        root = new TreeNode(num[mid]);
        dfs(root->left, left, mid - 1, num);
        dfs(root->right, mid + 1, right, num);
    }
};

